package org.offsync.apps

import java.nio.channels.SocketChannel

class EchoWorker extends Runnable {
  private val queue: java.util.List[ServerDataEvent] = new java.util.LinkedList[ServerDataEvent]()
  
  def processData(server: NioServer, socket: SocketChannel, data: Array[Byte], count: Int): Unit = {
    val dataCopy = new Array[Byte](count)
    System.arraycopy(data, 0, dataCopy, 0, count)
    queue.synchronized {
      queue.add(new ServerDataEvent(server, socket, dataCopy))
      queue.notify()
    }
  }
  
  def run(): Unit = {
    var dataEvent: ServerDataEvent = null
    
    while (true) {
      // Wait for data to become available
      queue.synchronized {
        while (queue.isEmpty()) {
          try {
            queue.wait()
          } catch { case e: InterruptedException =>
          }
        }
        
        dataEvent = queue.remove(0).asInstanceOf[ServerDataEvent]
      }
      
      // Return to sender
      dataEvent.server.send(dataEvent.socket, dataEvent.data)
    }
  }
}
